
import UIKit


extension UIImage
{
    class func withURL(_ url:String, _ block:((_ img:UIImage, _ url:String)->Void)?)->URLSessionTask?
    {
        let whereStr = String(format:"where %@=%@",bg_sqlKey("url"),bg_sqlValue(url))
        let array = KImage.bg_find(nil, where: whereStr)
        if array!.count > 0{
            let img = array![0] as! KImage
            block?(UIImage(data:img.data)!, url)
        }
        let stri = URL(string:url) ?? nil
        if stri == nil {
            return URLSessionTask()
        }
        let task = network.get(url, para: nil, header: nil, success: { img in
            let model = KImage()
            model.url = url
            model.data = (img as! UIImage).jpegData(compressionQuality: 0.5)!
            KImage.bg_saveOrUpdate([model])
            block?((img as! UIImage), url)
            print("")
        }, fail: { Errorerror in
            print("")
        })
        return task as! URLSessionTask
    }
    
    class func withColor(_ color:UIColor)->UIImage
    {
        let rect = CGRect(x:0, y:0, width:10.0, height: 10.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
    
    func base64()->String
    {
        let data = self.jpegData(compressionQuality:1.0)
        return data!.base64EncodedString(options:.endLineWithCarriageReturn)
    }
}
